<?php
declare (strict_types = 1);

namespace app\middleware;

use think\facade\Session;
use think\facade\Db;
use think\Response;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class AuthMiddleware
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 从请求头获取token
        $authHeader = $request->header('Authorization');
        if (empty($authHeader)) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        // 去掉可能存在的 Bearer 前缀
        $token = str_replace('Bearer ', '', $authHeader);

        try {
            // 解码并校验JWT
            $decoded = JWT::decode($token, new Key(config('jwt.secret'), 'HS256'));
            $uid = $decoded->uid ?? null;
            if (!$uid) {
                return json(['code' => 401, 'msg' => '无效的令牌']);
            }

            // 可选：校验发行方/受众
            if (!empty(config('jwt.issuer')) && isset($decoded->iss) && $decoded->iss !== config('jwt.issuer')) {
                return json(['code' => 401, 'msg' => '无效的令牌(issuer)']);
            }
            if (!empty(config('jwt.audience')) && isset($decoded->aud) && $decoded->aud !== config('jwt.audience')) {
                return json(['code' => 401, 'msg' => '无效的令牌(audience)']);
            }

            // 读取用户信息
            $user = Db::name('users')->where('id', $uid)->find();
            if (!$user) {
                return json(['code' => 401, 'msg' => '用户不存在或已被禁用']);
            }

            // 绑定到请求
            $request->user = (object)[
                'uid' => $user['id'],
                'username' => $user['username'] ?? '',
                'points' => $user['points'] ?? 0
            ];

            return $next($request);
        } catch (\Throwable $e) {
            return json(['code' => 401, 'msg' => '令牌无效或已过期']);
        }
    }
} 